using BackData;
using Domain.RBAC;
using Infratructure;
using MediatR;
using SqlSugar;
using Team.API.Applocation.Command.Users.Permissions;

namespace Team.API.Applocation.Handler.Users.Permissions
{
    /// <summary>
    /// 删除权限处理器
    /// </summary>
    public class DeletePermissionHandler : IRequestHandler<DeletePermissionCommand, APIResult<int>>
    {
        private readonly IRepository<Permissionmodel> permissionRepository;
        private readonly IRepository<Rolepermissionmiddle> rolePermissionRepository;

        public DeletePermissionHandler(
            IRepository<Permissionmodel> permissionRepository,
            IRepository<Rolepermissionmiddle> rolePermissionRepository)
        {
            this.permissionRepository = permissionRepository;
            this.rolePermissionRepository = rolePermissionRepository;
        }

        public async Task<APIResult<int>> Handle(DeletePermissionCommand request, CancellationToken cancellationToken)
        {
            // 查询权限是否存在
            var permission = await permissionRepository.GetByIdAsync(request.Id);
            if (permission == null || permission.IsDel)
            {
                return APIResult<int>.Faile("权限不存在");
            }

            // 检查是否有子权限
            bool hasChildren = await permissionRepository.GetAll()
                .Where(p => p.IsDel == false && p.ParentId == request.Id)
                .AnyAsync();

            if (hasChildren)
            {
                return APIResult<int>.Faile("该权限下有子权限，无法删除");
            }

            // 检查是否有角色使用该权限
            bool hasRoles = await rolePermissionRepository.GetAll()
                .Where(rp => rp.IsDel == false && rp.PermissionId == request.Id)
                .AnyAsync();

            if (hasRoles)
            {
                return APIResult<int>.Faile("该权限已分配给角色，无法删除");
            }

            // 软删除权限
            permission.IsDel = true;
            //permission.Updatedate = DateTime.Now;
            //permission.Updatename = "系统管理员"; // TODO: 从当前登录用户获取

            int rows = await permissionRepository.UpdateAsync(permission);
            if (rows <= 0)
            {
                return APIResult<int>.Faile("删除权限失败");
            }

            return APIResult<int>.Ok("删除权限成功", rows);
        }
    }
}
